package com.itheima.web.controller.system;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.User;
import com.itheima.service.system.DeptService;
import com.itheima.service.system.RoleService;
import com.itheima.service.system.UserService;
import com.itheima.utils.JedisUtils;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import java.util.*;

@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController {

    @Reference
    private UserService userService;

    @Reference
    private DeptService deptService;

    @Reference
    private RoleService roleService;

    @RequestMapping(value = "/list", name = "用户列表查询")
    public String list(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {

        PageInfo pageInfo = userService.findByPage(getCompanyId(), pageNum, pageSize);


        request.setAttribute("page", pageInfo);
        return "system/user/user-list";
    }


    @RequestMapping(value = "/toAdd", name = "跳转用户新增页面")
    public String toAdd() {
        // 准备所有部门信息
        List<Dept> deptList = deptService.findAll(getCompanyId());

        request.setAttribute("deptList", deptList);

        return "system/user/user-add";
    }


    @RequestMapping(value = "/toUpdate", name = "跳转用户修改页面")
    public String toUpdate(String id) {
        // 查询当前用户信息
        User user = userService.findById(id);
        user.setPassword(null);
        request.setAttribute("user", user);

        // 准备所有部门信息
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", deptList);

        return "system/user/user-update";
    }


    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping(value = "/edit", name = "用户新增或修改")
    public String edit(User user) {

        //密码加密
        String oldPassword = user.getPassword();
        if (StringUtils.isNotEmpty(oldPassword)) {
            String passwordWithMd5 = new Md5Hash(oldPassword, user.getEmail(), 2).toString();
            user.setPassword(passwordWithMd5);
        }

        if (StringUtils.isEmpty(user.getId())) {
            user.setId(UUID.randomUUID().toString());

            //设置公司信息
            user.setCompanyId(getCompanyId());
            user.setCompanyName(getCompanyName());
            userService.save(user);

            //当保存用户完毕之后,向用户邮箱发送一封邮件
            String to = user.getEmail();//收件人邮箱地址
            String title = "saas-export用户新建成功";//邮件标题
            String content = "恭喜您,你的saas平台用户创建成功,登录账号为当前邮箱,登录密码为:" + oldPassword;//邮件内容

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("to", to);
            map.put("title", title);
            map.put("content", content);

            amqpTemplate.convertAndSend("mail.sendmail", map);
            System.out.println("调用邮件平台完毕..................");
        } else {
            userService.update(user);
        }
        return "redirect:/system/user/list.do";
    }

    @RequestMapping(value = "/delete", name = "用户删除")
    public String delete(String id) {
        userService.delete(id);
        return "redirect:/system/user/list.do";
    }


    @RequestMapping(value = "/roleList", name = "跳转用户分配角色页面")
    public String roleList(String id) {
        //1. 显示出用户名称(查询用户信息)
        User user = userService.findById(id);
        request.setAttribute("user", user);

        //2. 显示出所有的角色, 等待勾选( 查询所有角色)
        List<Role> roleList = roleService.findAll(getCompanyId());
        request.setAttribute("roleList", roleList);

        //3. 回显当前用户已经分配了的角色 ( 查询中间表 )
        List<String> roleIds = userService.findRoleIdsByUserId(id);//1  2  3  --->1,2,3
        String userRoleStr = Arrays.toString(roleIds.toArray());
        request.setAttribute("userRoleStr", userRoleStr);

        //4. 跳转到给用户分配角色页面
        return "system/user/user-role";
    }


    @RequestMapping(value = "/changeRole", name = "用户分配角色")
    public String changeRole(@RequestParam("userid") String userId, String[] roleIds) {
        userService.changeRole(userId, roleIds);

        return "redirect:/system/user/list.do";
    }

    @RequestMapping(value = "/sendSMS", name = "验证码发送")
    @ResponseBody
    public String sendSMS(String telephone) {
        String signName = "黑马赫赫";
        String mb = "SMS_195585214";
        String code = RandomStringUtils.randomNumeric(6);
        String param = "{\"code\":\"" + code + "\"}";
        Map<String, String> map = new HashMap<>();
        map.put("signName",signName);
        map.put("mb",mb);
        map.put("telephone",telephone);
        map.put("param",param);
        System.out.println(code);
        amqpTemplate.convertAndSend("note.sendNote",map);
        System.out.println("调用短信平台完毕..................");
        /*SmsUtils smsUtils = new SmsUtils();
        smsUtils.sendSms(telephone, signName, mb, param);*/
        Jedis jedis = JedisUtils.getJedis();
        jedis.set("code" + telephone,code);
        return "1";
    }
    @RequestMapping(value = "/codeCheck", name = "验证码校验")
    @ResponseBody
    public String codeCheck(String telephone,String value) {
        Jedis jedis = JedisUtils.getJedis();
        String code = jedis.get("code" + telephone);
        if (code == null || !code.equals(value) || code == ""){
            return "false";
        }
        return "true";
    }
}
